<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\common\service;

class Utils
{
    /**
     * @notes 生成随机字符串
     * @param int $length
     * @return string
     */
    public static function randomStr(int $length = 32): string
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /**
     * 重组树形结构数据
     * @param $arr
     * @param $level
     * @param $id
     * @return array
     */
    public static function makeTree($arr, $level = 0, $id = 0)
    {
        $list = array();
        foreach ($arr as $k => $v) {
            if ($v['pid'] == $id) {
                $v['level'] = $level;
                $children = self::makeTree($arr, $level + 1, $v['id']);

                if (count($children) > 0) {
                    $v['children'] = $children;

                }

                $list[] = $v;
            }
        }
        return $list;
    }

    /**
     * @description: 获取一个日期范围内的日期
     * @param {interval:日期范围,type：取值类型，-：获取之前日期；+：获取之后的日期}
     * @return:
     */
    public static function getDateInterval(int $interval, string $type): array
    {
        $dateArr = [];
        for ($i = $interval - 1; $i >= 0; $i--) {
            array_push($dateArr, date('Y-m-d', strtotime("{$type}{$i} day")));
        }
        if ($type == '+') $dateArr = array_reverse($dateArr);
        return $dateArr;
    }
}